package dao;

import java.util.List;

import hibernateUtils.HibernateUtil;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import beans.ComandaBean;
import beans.ComisionBean;
import beans.ItemVentaBean;
import beans.VentaBean;

public class HibernateVentaDAO {

	private static HibernateVentaDAO instancia = null;
	private static SessionFactory sf = null;

	public static HibernateVentaDAO getInstancia() {
		if (instancia == null) {
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateVentaDAO();
		}
		return instancia;
	}

	public void grabarVenta(VentaBean vb) {
		// VentaBean vb=AdministradorVenta.getInstancia().fromModelTOBean(v);

		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(vb);
		;
		session.flush();
		session.getTransaction().commit();
		session.close();

	}

	public VentaBean getVenta(int nroMesa) {
		Session session = sf.openSession();
		Query q = session.createQuery("from VentaBean v where v.nroMesa=? ")
				.setInteger(0, nroMesa);
		q.setFirstResult(0).setMaxResults(1);
		Object o = q.uniqueResult();
		VentaBean venta = (VentaBean) o;
		return venta;

	}

	public void updateVenta(VentaBean vb) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.update(vb);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}

	public ComandaBean buscarComanda(VentaBean v) {
		Session session = sf.openSession();
		Query q = session
				.createQuery(
						"select c from VentaBean v join v.comandas"
								+ " c where v.idVenta=? and c.estado=?")
				.setInteger(0, v.getIdVenta()).setString(1, "no despachada");

		ComandaBean cb = (ComandaBean) q.uniqueResult();
		// session.flush();
		// sf.close();
		return cb;
	}

	public VentaBean buscarVenta(VentaBean ab) {
		Session session = sf.openSession();
		VentaBean venta = (VentaBean) session.get(VentaBean.class,
				ab.getIdVenta());
		session.close();
		return venta;
	}

	public ItemVentaBean buscarItemVenta(ItemVentaBean ab) {
		Session session = sf.openSession();
		ItemVentaBean item = (ItemVentaBean) session.get(ItemVentaBean.class,
				ab.getIdItemVenta());
		session.close();
		return item;
	}

	public VentaBean buscarUltimaVenta() {
		Session session=sf.openSession();
		List<VentaBean> ventas=(List<VentaBean>) session.createQuery("from VentaBean").list();
		session.close();
		return ventas.get(ventas.size()-1);
	}

	public void merge(VentaBean vb) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.merge(vb);
		session.flush();
		session.getTransaction().commit();
		session.close();
		
	}

}
